﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace wjy自制小框架.Common
{
    /// <summary>
    /// 生成随机可用端口
    /// wjy
    /// </summary>
    public class RandomPort
    {
        /// <summary>
        /// 生成随机可用端口
        /// </summary>
        public int genPort()
        {
            int minPort = 1024;
            int maxPort = 65535;
            return GetRandomPort(minPort, maxPort);
        }

        public int GetRandomPort(int minPort, int maxPort)
        {
            Random random = new Random();
            while (true)
            {
                int port = random.Next(minPort, maxPort);
                if (IsPortAvailable(port))
                {
                    return port;
                }
            }
        }

        public bool IsPortAvailable(int port)
        {
            bool isAvailable = true;
            using (TcpClient tcpClient = new TcpClient())
            {
                try
                {
                    tcpClient.Connect(IPAddress.Loopback, port);
                }
                catch (SocketException)
                {
                }
                isAvailable = !tcpClient.Connected;
            }
            return isAvailable;
        }
    }
}
